package com.xuanwu.mall.file.controller;

import com.xuanwu.mall.file.ceph.FileHandler;
import com.xuanwu.mall.util.common.RespResult;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * xuanwu-mall
 * com.xuanwu.mall.file.controller
 *
 * @Description:
 * @Author：xuanwudeshuijngye_26567
 * @Date 2024-03-18 09:47
 * @Company: 旋舞科技有限公司
 **/
@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private FileHandler fileHandler;
    /**
     * 文件上传
     *
     *
     **/
    @PostMapping("/upload")
    public RespResult upload(MultipartFile file) throws IOException {
        fileHandler.upload(file.getOriginalFilename(),file.getBytes());
        return RespResult.defaultSuccessResult();
    }

    /**
     * 文件下载
     *
     *
     **/
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        byte[] bytes = fileHandler.download(filename);
        ServletOutputStream os = response.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
